﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using AnalisisDeRiesgos.Dal;

namespace AnalisisDeRiesgos.Models.User
{
    [PasswordMatch("Password", "RePassword")]
    public class ChangePasswordModel
    {   
        [Required(ErrorMessage = "El nombre es requerido")]
        public int CI { get; set; }       
        public string FirstName { set; get; } // The First Name of the user
        public string LastName { set; get; } // The Last name of the user
        public string SecondLastName { set; get; } // The second last name of the user


        [DisplayName("Contraseña")]
        [DataType(DataType.Password)]        
        [StringLength(50, ErrorMessage = "La contraseña debe ser máximo de 50 caracteres y minimo 6 caracteres", MinimumLength = 6)]
        public String Password { set; get; } // The password that the user will input

        [DisplayName("Re escriba la contraseña")]
        [DataType(DataType.Password)]
        public String RePassword { set; get; } // The passowrd that the user must re input

        private riskanalysisEntities entities = new riskanalysisEntities(); // A reference to Entities

        public void FillUserById(int id)
        {
            var userList = from u in entities.users
                           where u.CI == id && u.enabled
                           select u;

            if (userList.Count() <= 0)
                throw new EditUserException("El usuario especificado no fue encontrado");

            user theUser = userList.First();

            CI = theUser.CI;
            FirstName = theUser.firstName;
            LastName = theUser.lastName;
            SecondLastName = theUser.secondLastName;            
            Password = "";
            RePassword = "";
        }

        public void Save()
        {
            var userList = from u in entities.users
                           where u.CI == CI && u.enabled
                           select u;

            if (userList.Count() <= 0)
                throw new EditUserException("El usuario especificado no fue encontrado");

            user theUser = userList.First();           

            if (!String.IsNullOrEmpty(Password))
            {
                theUser.password = Utils.CalculateSHA1(Password);
            }
            
            entities.SaveChanges();
        }
    }
}